#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2009 Denis Mingulov
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#


import os
import wsgiref.handlers

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from google.appengine.dist import use_library
use_library('django', '1.1')

from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.api import memcache

from engine import modules
from engine import persons
from engine import fighter

class MainHandler(webapp.RequestHandler):
    def get_page_data(self):
        pers = persons.getCurrentPerson()
        state = fighter.Fighter(person = pers)
        pers.addToFighter(state)

        modlist = persons.getActiveModules(pers, True)

        for item in modlist:
            item.addToFighter(state)

        # generate values
        state.generateSpecialAbilitiesTable()

        state.calculatePersonSpecialAbilities()

        state.calculateDifferentShipValues1()
        state.calculateShipSpecialAbilities1()

        state.calculateDifferentShipValues2()
        state.calculateShipSpecialAbilities2()

        state.calculateShipMaxLife2()

        query = modules.Weapon.gql("WHERE person = :1 AND status>0", pers.key())
        weapon = query.fetch(1000);

        for item in weapon:
            item.distance = state.calculateWeaponDistance(item.distance)
            item.accuracy = state.calculateWeaponAccuracy(item.accuracy)
            item.minshot = state.calculateWeaponMinShot(item.minshot)
            item.maxshot = state.calculateWeaponMaxShot(item)
            pass
     
        template_values = {
            'fighter': state,
            'pers': pers,
            'weapon': weapon,
            }

        path = os.path.join(os.path.dirname(__file__), 'templates/result.html')
        data = template.render(path, template_values)
        return data


    def get(self):
        if not users.get_current_user():
            self.redirect('/')
            return

        self.response.out.write(self.get_page_data())

    def post(self):
        self.get()

def real_main():
    application = webapp.WSGIApplication([('/result', MainHandler)], debug=True)
    wsgiref.handlers.CGIHandler().run(application)

def profile_main():
    # This is the main function for profiling
    # We've renamed our original main() above to real_main()
    import cProfile, pstats
    prof = cProfile.Profile()
    prof = prof.runctx("real_main()", globals(), locals())
    print "<pre>"
    stats = pstats.Stats(prof)
    stats.sort_stats("time")  # Or cumulative
    stats.print_stats(80)  # 80 = how many to print
    # The rest is optional.
    # stats.print_callees()
    # stats.print_callers()
    print "</pre>"

main = real_main

if __name__ == '__main__':
    main()

